package br.com.async.infrastructure.impl;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.com.async.domain.person.Person;
import br.com.async.domain.person.PersonRepository;
import br.com.async.domain.person.PersonType;
import br.com.async.infrastructure.AbstractRepositoryImpl;
import br.com.async.util.ResponseData;

public class PersonRepositoryImpl extends
		AbstractRepositoryImpl<Person, Integer> implements PersonRepository {

	public PersonRepositoryImpl() {
		super(Person.class);
	}

	public ResponseData<Person> findResponsibleName(String name, int offset,
			int maxResult) {

		ResponseData<Person> rd = new ResponseData<Person>();
		Criteria criteria = getSession().createCriteria(Person.class);
		criteria.add(Restrictions.eq("personType", PersonType.RESPONSIBLE));

		criteria.add(Restrictions.ilike("name", name, MatchMode.ANYWHERE));
		rd.setQuantityRowsFromQuery(criteria.list().size());

		if (maxResult > 0)
			criteria.setMaxResults(maxResult);
		if (offset > 0)
			criteria.setFirstResult(offset);

		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		criteria.addOrder(Order.asc("code"));

		rd.setItems(criteria.list());

		return rd;
	}

	public ResponseData<Person> listReponsibles(int offset, int maxResult) {
		ResponseData<Person> rd = new ResponseData<Person>();

		Criteria criteria = getSession().createCriteria(Person.class);
		criteria.add(Restrictions.eq("personType", PersonType.RESPONSIBLE));

		rd.setQuantityRowsFromQuery(criteria.list().size());

		if (maxResult > 0)
			criteria.setMaxResults(maxResult);
		if (offset > 0)
			criteria.setFirstResult(offset);

		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		criteria.addOrder(Order.asc("code"));

		rd.setItems(criteria.list());

		return rd;
	}

}
